import BaseService from './base';
import Sequelize from 'sequelize';
import db from '../models';

const Op = Sequelize.Op;

export default class OptionsService extends BaseService {
  constructor({ optionsDao }) {
    super();
    this.optionsDao = optionsDao
  }

  // 获取配置信息
  async getOptionsAll () {
    try {
      const rows = await db.sequelize.query(`SELECT * FROM t_options a
        LEFT JOIN t_customer b ON a.t_customer = b.id
        LEFT JOIN t_logos c ON a.t_logos = c.id
        WHERE a.mark != 1`, {
        type: db.sequelize.QueryTypes.SELECT
      })
      return this.success('获取成功', rows);
    } catch (err) {
      return this.fail('获取失败', null, err);
    }
  }

  async getOptionslist(options) {
    try {
      const rows = await db.sequelize.query(`SELECT * FROM t_options a
        LEFT JOIN t_customer b ON a.t_customer = b.id
        LEFT JOIN t_logos c ON a.t_logos = c.id
        WHERE a.mark != 1 AND a.t_no = "${options.t_no}"`, {
        type: db.sequelize.QueryTypes.SELECT
      })
      return this.success('获取成功', rows);
    } catch (err) {
      return this.fail('获取失败', null, err);
    }
  }

  async addOptions(options) {
    const [exsitErr, itemExsit] = await this.optionsDao.findOne({
      where: {
        t_no: options.t_no
      }
    });
    if (exsitErr) {
      return this.fail('添加失败', null, exsitErr);
    }
    if (itemExsit) {
      return this.fail('已存在');
    }
    const [addErr] = await this.optionsDao.addOptions(options);
    if (addErr) {
      return this.fail('添加失败', null, addErr);
    }
    return this.success('添加成功')
  }

  async delOptions(options) {
    const [err, updateOptions] = await this.optionsDao.delete({
      where: {
        t_no: options.t_no
      }
    });
    if (err) {
      return this.fail('删除失败');
    }
    return this.success('删除成功');
  }

  async updateOptions(options) {
    const [err, updateOptions] = await this.optionsDao.update(options, {
      where: {
        t_no: options.t_no
      }
    });
    if (err) {
      return this.fail('更新失败');
    }
    return this.success('更新成功');
  }
}